<template>
  <div class="subPage">
    <div style="position: absolute;left: -99999px;top: -99999px;">
      <mpvue-cropper
        ref="cropper"
        :option="cropperOpt"
        ></mpvue-cropper>
    </div>
    <div class="subTop">
      <div class="tips">
        <span>拍摄/上传您的二代身份证</span>
        <img  :src="wenhaoImg" style="width: 38rpx;height: 38rpx; margin-left: 12rpx;" @click="konwCard"/>
      </div>
      <div class="imgDiv">
        <span class="btnImg">
          <img v-if="topSrc&&isreal==false" :src="deleteImg"  @click="deleteCert('FRONT')"/>
        </span>
        <div style="position: relative;">
          <image v-if="!topSrc" :src="cardTopImg" @click="showActive('FRONT')" mode='widthFix' class="Img"></image>
          <image v-if="topSrc"  :src="topSrc" mode='scaleToFill' class="Img" ></image>
          <i-spin size="small" fix v-if="frontSpin && false" custom>
            照片处理中...
          </i-spin>
        </div>
        <span class="btnImg">
          <img v-if="topSrc" :src="fangdaImg" @click="showImg('FRONT')"/>
        </span>
      </div>
      <!-- style="transform: rotate(-90deg)" -->
      <div class="imgDiv">
        <span class="btnImg">
          <img :src="deleteImg" v-if="btmSrc&&isreal==false" @click="deleteCert('BACK')"/>
        </span>
        <div style="position: relative;">
          <image v-if="!btmSrc" :src="cardBtmImg" @click="showActive('BACK')" mode='widthFix' class="Img"></image>
          <image v-if="btmSrc"  :src="btmSrc" mode='scaleToFill' class="Img" ></image>
          <i-spin size="small" fix v-if="backSpin && false" custom>
            照片处理中...
          </i-spin>
        </div>
        <span class="btnImg">
          <img :src="fangdaImg" v-if="btmSrc" class="btnImg" @click="showImg('BACK')"/>
        </span>
      </div>
    </div>
    <div class="subBtm">
      <button v-if="topSrc && btmSrc && isreal==false " @click="sureUpload">下一步</button>
    </div>
    <cover-view class="zoon" v-if="knowStatus">
      <cover-view class="init">
        <cover-view>证件上传示例</cover-view>
        <cover-image :src="cardTipsImg"></cover-image>
        <cover-view class="know" @click="knowClose">知道了</cover-view>
      </cover-view>
    </cover-view>
    <div class='coverView clearfix' v-if='photoStatus'>
      <camera mode="normal" device-position="back" flash="auto" class='cameraDiv clearfix' v-if="!surePhoto">
        <cover-image class='itemClose fr clearfix' :src="guanbiImg" @click='closePhoto' ></cover-image>
        <cover-view class='photoTis clearfix' v-if="chooseName == 'FRONT'">扫描身份证人像面，并尝试对齐边缘</cover-view>
        <cover-view class='photoTis clearfix' v-if="chooseName == 'BACK'">请将国徽面放在框内，并调好光线</cover-view>
        <cover-image class='cardBack' :src="frontImg" v-if="chooseName == 'FRONT' && !surePhoto"></cover-image>
        <cover-image class='cardBack' :src="backImg" v-if="chooseName == 'BACK' && !surePhoto"></cover-image>
      </camera>
      <cover-view class='imgDiv clearfix' v-if="surePhoto">
        <cover-view class='photoTis clearfix'></cover-view>
        <cover-image  class='cardPhoto' mode="aspectFit" v-if='imgSrc' :src="imgSrc"></cover-image>
      </cover-view>
      <div class="btnBotton clearfix">
        <div class="fl div1" v-if="surePhoto" @click="moreTime">重　拍</div>
        <div class="borderOut" @click="takePhoto" v-if="!surePhoto">
          <div></div>
        </div>
        <div class="fr div2" v-if="surePhoto" @click="nextTime(imgSrc)">下一步</div>
      </div>
    </div>
    <cover-view class="sheet" v-if="visible">
      <cover-view class="sheetBtm">
        <cover-view @click="onSelect(1)">拍照</cover-view>
        <cover-view @click="onSelect(2)">从手机相册选择</cover-view>
        <cover-view @click="handleCancel">取消</cover-view>
      </cover-view>
    </cover-view>
    <i-message id="message" />
     <i-toast id="toast" />
  </div>
</template>

<script>
  const { $Toast, $Message } = require('../../../../../static/iview/base');
  import api from '@/api/api'
  import storage from '@/utils/storage'
  import Bus from '@/utils/bus.js'
  const device = mpvue.getSystemInfoSync()
  const width = device.windowWidth
  const height = device.windowHeight - 50
  let wecropper = null
  import MpvueCropper from 'mpvue-cropper'
  export default {
    data () {
      return {
        accountInfo: {},
        chooseName: '', // 选择上传还是拍照的名字
        knowStatus: false,
        topSrc: '', // 正面
        topKey: '',
        btmSrc: '', // 背面
        btmKey: '',
        photoStatus: false, // 拍照的状态
        ctx: null, // 照相组件
        canvas: null,  // 画布组件
        titleHeight: 0, //
        visible: false, // 选择上传还是拍照
        user_res:{},
        isreal:false,
        actions: [
          // {
          //   name: '拍照',
          //   value: 1
          // },
          {
            name: '从手机相册选择',
            value: 2
          }
        ],
        cardImageInfo: {},
        surePhoto: false, // 拍照了
        imgSrc: '', // 拍照暂存
        rpx: 1,
        // backSpin: true,
        // frontSpin: true
        backSpin: false,
        frontSpin: false,
        regular_id:"",
        cropperOpt: {
          id: 'cropper',
          targetId: 'targetCropper',
          pixelRatio: device.pixelRatio,
          width,
          height,
          scale: 2.5,
          zoom: 8,
          cut: {
            x: (width - 315) / 2,
            y: (height - 180) / 2,
            width: 315,
            height: 185
          },
          boundStyle: {
            color: '#0088FF',
            mask: 'rgba(0,0,0,0.8)',
            lineWidth: 1
          }
        },
        imgUrl: '',
        wenhaoImg: '',
        cardTopImg: '',
        fangdaImg: '',
        cardBtmImg: '',
        cardTipsImg: '',
        guanbiImg: '',
        frontImg: '',
        backImg: '',
        deleteImg: '',
        errIcon: ''
      }
    },
    components: {
      MpvueCropper
    },
    onUnload(){
      this.topSrc = ''
      this.topKey = ''
      this.btmSrc = ''
      this.btmKey = ''
      this.regular_id = ''
      this.isreal = false
    },
    onShow () {
      let that = this
      that.knowStatus = false
      that.visible = false
      mpvue.getStorage({
        key: 'imageInfo',
        success (res) {
          that.cardImageInfo = res.data
        },
        complete () {
          if (that.cardImageInfo.type) {
            console.log('that.cardImageInfo ',that.cardImageInfo )
            if(!that.topSrc&&!that.topKey&&that.cardImageInfo.type=='FRONT'){
              that.chooseName = that.cardImageInfo.type
              that.nextTime(that.cardImageInfo.imgSrc)
              mpvue.removeStorage({
                key: 'imageInfo'
              })
            }
            if(!that.btmSrc&&!that.btmKey&&that.cardImageInfo.type=='BACK'){
              that.chooseName = that.cardImageInfo.type
              that.nextTime(that.cardImageInfo.imgSrc)
              mpvue.removeStorage({
                key: 'imageInfo'
              })
            }

          } else {
            that.echo()
          }
        }
      })
      setTimeout(() => {
          mpvue.removeStorage({
            key: 'imageInfo'
          })
      }, 500)
      // setTimeout(() => {
      //     mpvue.removeStorage({
      //       key: 'imageInfo'
      //     })
      // }, 1500)
    },
    onLoad (options) {
      this.topSrc = ''
      this.topKey = ''
      this.btmSrc = ''
      this.btmKey = ''
      let that = this
      that.knowStatus = false
      that.visible = false
      that.photoStatus = false
      that.cardImageInfo = {}
      var antactInfo = this.$storage.getContact()
      console.log('antactInfo',antactInfo)
      if(antactInfo.topSrc){
        that.topSrc = antactInfo.topSrc
        that.topKey = antactInfo.topKey
      }
      if(antactInfo.btmKey){
        that.btmSrc = antactInfo.btmSrc
        that.btmKey = antactInfo.btmKey
      }
      if(options.id){
          this.regular_id = options.id
          // this.echo()
      }
      if (options.is_real) {
        this.isreal = options.is_real
      }
      this.imgUrl = api.imgUrl
      this.wenhaoImg = this.imgUrl + 'wenhao.png'
      this.cardTopImg = this.imgUrl + 'cardTop.png'
      this.fangdaImg = this.imgUrl + 'fangda.png'
      this.cardBtmImg = this.imgUrl + 'cardBtm.png'
      this.cardTipsImg = this.imgUrl + 'cardTips.png'
      this.guanbiImg = this.imgUrl + 'guanbi.png'
      this.frontImg = this.imgUrl + 'front.png'
      this.backImg = this.imgUrl + 'back.png'
      this.errIcon = this.imgUrl + 'err_icon.png'
      this.deleteImg = this.imgUrl + 'delete.png'
      this.ctx = mpvue.createCameraContext()
    },
    mounted () {
      wecropper = this.$refs.cropper
    },
    methods: {
      // 查看图片
      showImg (name) {
        let that = this
        let arr = []
        let src = ''
        if (name === 'FRONT' && that.topSrc) {
           arr.push(that.topSrc)
           src = that.topSrc
        } else if ((name === 'BACK' && that.btmSrc)){
           arr.push(that.btmSrc)
           src = that.btmSrc
        }
        if (arr.length > 0) {
          mpvue.offAppHide()
          mpvue.previewImage({
            current: src, // 当前显示图片的http链接
            urls: arr
          })
        }
      },
      // 删除图片
      deleteCert (name) {
        let that = this
        mpvue.showModal({
          title: '提示',
          content: '是否删除该照片?',
          success (res) {
            if (res.confirm) {
              if (name === 'FRONT') {
                that.topSrc = ''
                that.topKey = ''
              } else {
                that.btmSrc = ''
                that.btmKey = ''
              }
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      },
      // 查询以前上传的图片
      echo () {
        var that = this
        console.log('this.regular_id',this.regular_id)
        if(!this.regular_id){
          //新增无regular_id
          return
        }
        let data = {
          regular_id:this.regular_id
        }
        that.$api.user_query_regular(data, {'showLoading': true}).then(function (res) {
            console.log(res.data)
            that.userData = res.data
            if(that.userData.cert_front_url){
              that.topSrc = that.userData.cert_front_url
              that.topKey = that.userData.cert_front
            }
            if(that.userData.is_real==1&&that.userData.cert_front_url&&that.userData.cert_back_url){
              that.isreal = true
            }
            if(that.userData.cert_back_url){
              that.btmSrc = that.userData.cert_back_url
              that.btmKey = that.userData.cert_back
            }
            that.frontSpin = false

        })
      },
      // 选择方式
      onSelect (event) {
        this.visible = false
        // if (event === 1) {
        //   this.photoStatus = true
        // } else {
        //   // this.chooseCard(this.chooseName)
        //   this.$router.push(`/pages/qualification/child/choosecard/main?type=${this.chooseName}`)
        // }
        var that = this
        this.visible = false
        if (event === 1) {
             wx.getSetting({
              success: function (res) {
                if (!res.authSetting['scope.camera']) {
                  wx.authorize({
                    scope: 'scope.camera',
                    success: function () {},
                    fail: function () {
                      wx.showToast({
                        image: that.errIcon,
                        title: '相机授权失败'
                      })
                      // return
                      setTimeout(()=>{
                        console.log(111)
                          wx.openSetting({      //这里的方法是调到一个添加权限的页面，可以自己尝试
                          success: (res) => {
                            if (!res.authSetting['scope.camera']) {
                              wx.authorize({
                                scope: 'scope.camera',
                                success() {
                                  console.log('授权成功')
                                }, fail() {
                                  console.log('用户点击取消')
                                }
                              })
                            }
                            }
                          })

                      },1000)
                    }
                  })
                }else{
                  that.photoStatus = true
                }
              },
              fail: function () {
                wx.showToast({
                  image: that.errIcon,
                  title: '授权失败'
                })
                return
              }
            })
        }else{
           that.$router.push(`/pages/qualification/child/choosecard/main?type=${that.chooseName}`)
           return
        }


      },
      // 确认并提交
      sureUpload () {
        let that = this
        if (!that.topSrc) {
          $Toast({
            content: '请拍摄/上传您的二代身份证人像面',
            type: 'warning'
          })
          return
        }
        if (!that.btmSrc) {
          $Toast({
            content: '请拍摄/上传您的二代身份证国徽面',
            type: 'warning'
          })
          return
        }
        var obj = {
          topKey:this.topKey,
          btmKey:this.btmKey,
          way:'cert'
        }
        Object.assign(that.user_res,obj)
        console.log('that.user_res',that.user_res)
        that.$storage.setContact(that.user_res)
        that.$storage.setUserres(that.user_res)
        this.$router.push({
          path:'/pages/qualification/child/audit/main?isCommon=true',
        })
        // that.$router.push(`/pages/center/child/addCommon/main?topKey=${this.topKey}&btmKey=${this.btmKey}`)
      },
      // 下一步
      nextTime (src) {
        // let token = ''
        if (!src) {
          return
        }
        console.log(src,new Date(), '进到nextTime方法111')
        let that = this
        that.photoStatus = false
        wx.showLoading({
          title: "上传中...",
          mask: true
        });
        if (that.chooseName == 'BACK') {
            that.btmSrc = src  //取本地的src
          } else {
            that.topSrc = src  // 取本地的src
          }

        mpvue.uploadFile({
          url: api.host + '/api/user/card_id/upload/new',
          filePath: src,
          name: 'file',
          success (res){
            let dataInfo = JSON.parse(res.data)
            if (that.chooseName == 'BACK') {
              // that.btmSrc = src  //取本地的src
              that.btmKey = dataInfo.data.file_key
            } else {
              // that.topSrc = src  // 取本地的src
              that.topKey = dataInfo.data.file_key
            }
            that.$api.userCardIdDistinguish({card_side: that.chooseName, file_key: dataInfo.data.file_key}, {'showLoading': false}).then(function (res) {
              mpvue.hideLoading()
              if (that.chooseName == 'BACK') {
                $Message({
                  content: '上传成功',
                  type: 'success'
                })
              } else {
                that.user_res = res.data.resp  // 身份证正面保存信息
              if (that.user_res.Birth.length === 0 || that.user_res.Name.length === 0 || that.user_res.Sex.length === 0) {
                  $Message({
                    content: '识别失败,请重新上传',
                    type: 'warning'
                  })
                  that.topSrc = ''
                  that.topKey = ''
                } else {
                  $Message({
                    content: '上传成功',
                    type: 'success'
                  })
                }
              }
            }).catch ((e) => {
              if (that.chooseName == 'BACK') {
                that.btmSrc = ''
                that.btmKey = ''
              } else {
                that.topSrc = ''
                that.topKey = ''
              }
            })
          },
          file (e) {
            if (that.chooseName == 'BACK') {
              that.btmSrc = ''
              that.btmKey = ''
            } else {
              that.topSrc = ''
              that.topKey = ''
            }
          }
        })

      },
      // 重拍
      moreTime () {
        this.surePhoto = false
        this.imgSrc = ''
      },
      takePhoto () {
        let that = this
        that.ctx.takePhoto({
          quality: 'normal',
          success: (res) => {
            wecropper.pushOrigin(res.tempImagePath)
            setTimeout(() => {
              wecropper.getCropperImage({ original: true })
                .then((src) => {
                  that.surePhoto = true
                  that.imgSrc = src
                  // wx.redirectTo({
                  //   url: `/pages/thirdPage/child/real/main?type=${that.chooseName}&imgSrc=${src}`
                  // })
                  // that.nextTime(src)
                })
                .catch(e => {
                  console.error('获取图片失败')
                })
            }, 500)
          }
        })
      },
      // 关闭拍照
      closePhoto () {
        this.photoStatus = false
      },
      // 查看规范
      konwCard () {
        this.knowStatus = true
      },
      // 关闭规范
      knowClose () {
        this.knowStatus = false
      },
      // 弹出选择方式
      showActive (name) {
        if (this.backSpin || this.frontSpin) {
          if (this.backSpin) {
            $Toast({
              content: '请等待国徽面照片处理完成',
              type: 'warning'
            })
          } else {
            $Toast({
              content: '请等待人像面照片处理完成',
              type: 'warning'
            })
          }
          return
        }
        this.chooseName = name
        this.visible = true
        this.surePhoto = false
        this.imgSrc = ''
      },
      // 关闭选择方式
      handleCancel () {
        this.visible = false
      }
    }
  }
</script>

<style scoped lang='less'>
  .subPage {
    position: relative;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    .cropper-wrapper{
      position: relative;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      justify-content: center;
      height: 100%;
      background-color: #e5e5e5;
    }
    .coverView {
      width: 100%;
      height: 100%;
      position: absolute;
      /* background: #010101; */
      display: flex;
      flex-direction: column;

      .imgDiv {
        flex: 1;
        background: #000;
        .photoTis {
          height:20px;
          margin-top: 50px;
          margin-bottom: 20px;
        }
        .cardPhoto {
          width: 315px;
          height: 185px;
          margin: 0 auto;
        }
      }
      .cameraDiv {
        flex: 1;
        position: relative;
        .itemClose {
          /* display: inline-block; */
          width: 20px;
          height: 40rpx;
          margin: 30rpx 30rpx 0 0;
        }
        .photoTis {
          width: 500rpx;
          margin: 0 auto;
          height:20px;
          font-size:28rpx;
          font-family:PingFangSC-Regular,PingFangSC;
          font-weight:400;
          color:rgba(255,255,255,1);
          line-height:20px;
          padding: 15rpx 23rpx;
          background:rgba(1,1,1,1);
          border-radius:16px;
          opacity:0.2;
          color: #FFFFFF;
          text-align: center;
          margin-top: 100px;
          /* margin-bottom: 50px; */
        }
        .cardBack {
          width: 315px;
          height: 185px;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-left: -157.5px;
          margin-top: -92.5px;
          /* width: 315px;
          height: 185px;
          margin: 0 auto; */
        }
      }
      .btnBotton {
        width: 100%;
        height: 260rpx;
        background: #010101;
        .borderOut {
          width: 100rpx;
          height: 100rpx;
          border: 20rpx solid #fff;
          border-radius: 100%;
          margin: 0 auto;
          margin-top: 60rpx;
          div {
           width: 80rpx;
           height: 80rpx;
           background: #fff;
           border-radius: 100%;
           margin: 10rpx;
          }
        }
        .div1 {
          height: 40rpx;
          line-height: 40rpx;
          font-size: 30rpx;
          background: #3E3E3E;
          border-radius:8px;
          padding: 10rpx 30rpx;
          color: #fff;
          margin: 80rpx 0 0 50rpx;
        }
        .div2 {
          height: 40rpx;
          line-height: 40rpx;
          font-size: 30rpx;
          padding: 10rpx 30rpx;
          background:rgba(0,136,255,1);
          border-radius:8px;
          color: #fff;
          margin: 80rpx 50rpx 0 0;
        }
      }
    }
    .subTop {
      flex: 1;
      margin: 0 30rpx;
      .tips {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 38rpx;
        line-height: 38rpx;
        margin: 68rpx 0 64rpx 0
      }
      .imgDiv {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 50rpx;
        position: relative;
        .btnImg {
          flex: 1;
          img {
            width: 60rpx;
            height: 60rpx;
          }
        }
        .Img {
          width: 538rpx;
          height: 360rpx;
          margin: 0 15rpx;
          background:rgba(255,255,255,1);
          border-radius: 10rpx;
        }
      }
    }
    .zoon {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,.7);
      opacity: 1;
      z-index: 100;
      .init {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -290rpx;
        margin-top: -375rpx;
        z-index: 999;
        background: #fff;
        width: 580rpx;
        height: 750rpx;
        border-radius:18px;
        border:1px solid rgba(242,241,241,1);
        overflow: hidden;
        cover-view:nth-child(1) {
          height: 80rpx;
          font-size: 36rpx;
          font-family: PingFangSC;
          font-weight: 500;
          color: rgba(51,51,51, 1);
          line-height: 80rpx;
          text-align: center;
          margin-top: 34rpx;

        }
        .know {
          font-size: 34rpx;
          font-family: PingFangSC;
          font-weight: 500;
          color: #0088FF;
          text-align: center;
          padding-top: 30rpx;
          // border-top: 1rpx solid #f3f3f3!important;
        }
        cover-image {
          height: 435rpx;
          width: 530rpx;
          padding: 43rpx 25rpx 57rpx 25rpx;
          border: 1px solid #f3f3f3;
        }
      }
    }
    .sheet {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,.7);
      opacity: 1;
      .sheetBtm {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        text-align: center;
        color: #333333;
        cover-view {
          height: 100rpx;
          line-height: 100rpx;
          background: #fff;
          border-top: 1rpx solid rgba(242,241,241,1);
        }
      }
    }
    .subBtm {
      height: 90rpx;
      margin: 30rpx;
      button {
        font-size:34rpx;
        color: #fff;
        height: 90rpx;
        line-height: 90rpx;
        width: 100%;
        background: #3F4ADE;
      }
    }
  }
</style>
